<template>
  <div class="gm-wrapper">
    <div v-for="(item, idx) in state.list" :key="idx" class="box">
      <div class="del" @click="onRemove(item)">
        <close-circle-outlined />
      </div>
      <img :src="item.thumb">
    </div>
    <a-button v-if="state.selectLimit > state.list.length" type="primary" @click="onOpen">选择</a-button>
  </div>
  <a-modal v-model:visible="state.visible" title="选择商品" width="600px">
    <a-input-search
      v-model:value="state.keyword"
      placeholder="请输入名称模糊搜索"
      size="large"
      @search="onSearch"
    />
    <a-table
      :data-source="dataSource" :columns="columns" :row-selection="rowSelection" size="small"
      :loading="loading"
      :pagination="pagination"
      :row-key="record=>record.id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'thumb'">
          <a-image :width="40" :src="record.thumb" :fallback="errorImage" />
        </template>
        <template v-if="column.key === 'name'">
          <a>
            {{ record.name }}
          </a>
        </template>
        <template v-if="column.key === 'action' &&!props.multi">
          <a @click="onPicking(record)">
            选中
          </a>
        </template>
      </template>
    </a-table>
    <template #footer>
      <div v-if="props.multi == true">
        <a-button type="primary" @click="onConfirmPick">确认选中</a-button>
      </div>
    </template>
  </a-modal>
</template>
<script setup>
import { reactive, computed } from 'vue'
import usePager from '@/core/hooks/useRequestPager'
import brandApi from '@/api/goods/BrandApi'
import { errorImage } from '@/core/config/constant'
const props = defineProps({
  modelValue: {type: Object, default: null},
  limit: {type: Number, default: 8},
  multi: {type: Boolean, default: false}
})
const emits = defineEmits(['update:modelValue'])
const state = reactive({
  visible: false, 
  selectedRowKeys: [],
  selectedList: [],
  list: computed({
    get(){
      if(props.modelValue instanceof Array){
        return props.modelValue
      }
      return ( props.modelValue instanceof Object && !Array.isArray(props.modelValue)) ?  [props.modelValue]  : (props.modelValue==null||props.modelValue==undefined)? [] : [props.modelValue]
    },
    set(v){ 
      if(props.multi) {
        emits('update:modelValue', v)
      }else{
        if(v.length == 0) {
          emits('update:modelValue', null)
        } else{
          emits('update:modelValue', v[0])
        }
      }
    }
  }),
  selectLimit: computed({
    get(){
      return (props.multi) ? props.limit:1
    }
  })
})
const columns =computed(()=>{
  if(props.multi) {
    return  [
      { title: '图片', dataIndex: 'age',  key: 'age', width: '100px'},
      { title: '名称',  dataIndex: 'name',  key: 'name'}
    ]
  }else{
    return  [
      { title: '选中',  key: 'action', width: '80px'},
      { title: '图片', dataIndex: 'thumb',  key: 'thumb', width: '100px'},
      { title: '名称',  dataIndex: 'name',  key: 'name'}
    ]
  }
}) 
// 是否显示多选项
const rowSelection= computed(()=>{
  if(props.multi) {
    return  {selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange}
  }else{
    return false
  }
}) 
// 表格选中
const onSelectChange=(selectedRowKeys)=>{
  state.selectedRowKeys = selectedRowKeys
}
// 获取分页数据
const {
  loading,
  dataSource,
  pagination,
  handleTableChange, handleSearch
} = usePager(brandApi.getOptionsByPage)

// 移去商品
const onRemove=(item)=>{
  let data = state.list.filter(it=>it.id != item.id )
  state.list = data
  //console.log(JSON.stringify(data))
}
// 选中商品(单选)
const onPicking=(item)=>{
  if(!state.list.some(it=> item.id== it.id)){
    state.selectedList.push(item)
    //
    let arrs = state.selectedList.map(item=>{
      return item
    })
    state.list.push(...arrs)
    state.list = state.list.slice(0, state.selectLimit)
  }
  state.visible = false
}

// 选中商品(多选)
const onConfirmPick=()=>{
  let arrs = state.selectedRowKeys
    .filter(id=>!state.list.some(a=> a.id==id))
    .map(key=> state.dataSource.find(b=>b.id==key))
  //
  state.list.push(...arrs)
  state.list = state.list.slice(0, state.selectLimit)
  
  state.visible = false
}

// 打开选择对话框
const onOpen =()=>{
  state.selectedList = []
  state.keyword =''
  state.selectedRowKeys = []
  state.visible = true
}
// 获取数据
// 搜索 
const onSearch = ()=>{
  state.selectedRowKeys =[]
  let queryData = {searchKey: state.keyword}
  handleSearch(queryData)
}
</script>
<style lang="less" scoped>
.gm-wrapper {
  display: flex;
  flex-flow: row wrap;
  .box {
    overflow: hidden; margin-right: 5px;
    position: relative;
    border: 1px solid rgb(230, 227, 227);
    width: 60px; height: 60px;
    border-radius: 3px;
    img { width: 100%;height: 100%; border: 2px solid transparent;border-radius: 3px;}
    .del {
      position: absolute; top: 0px;right: 0px;
      padding: 2px 5px;
      backdrop-filter: blur(1px);
      font-size: 16px; 
      color: #FFF; 
      font-weight: 900;
      box-shadow: 0 4px 8px 0 rgba(3, 192, 66, 0.2);
      border: 1px solid #ffffff;
      border-radius: 5px;
      &:hover {
        color: rgb(235, 8, 8);
        border: 2px solid rgb(235, 8, 8);
        backdrop-filter: blur(13px);
      }
    }
    
  }
}
</style>